package com.util;

import com.util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class App {
    private static final Random random = new Random(20221223);
    private static final String s = "abcdefghijklmnopqrstuvwxyz";

    public static String randomString() {
        // 1) 随机一个数字，作为字符串长度，[5, 10]
        // 随机一个 [0, 6)
        int n = random.nextInt(6);
        n += 5;     // [5, 11)

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < n; i++) {
            int idx = random.nextInt(26);
            char c = s.charAt(idx);
            sb.append(c);
        }

        return sb.toString();
    }

    public static List<String> generateRandomStringList(int n) {
        List<String> list = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            list.add(randomString());
        }

        return list;
    }

    private static void insertBatch(List<String> list, int m, String table) throws SQLException {
        try (Connection c = DBUtil.connection()) {
            c.setAutoCommit(false); // 关闭自动提交

            String sql = String.format("insert into %s (name) values (?)", table);
            // 为了提升插入效率，只维护一个 PreparedStatement 对象即可，不断地重新绑定即可
            try (PreparedStatement ps = c.prepareStatement(sql)) {
                for (int i = 0; i < list.size(); i++) {
                    String rs = list.get(i);
                    ps.setString(1, rs);
                    ps.executeUpdate();

                    if ((i + 1) % m == 0) {
                        System.out.printf("插入 %s 了 %d 条数据\n", table, i + 1);
                        c.commit();
                    }
                }
            }
        }
    }

    public static void main(String[] args) throws SQLException {
        List<String> list = generateRandomStringList(1_00);
        int m = 10;

        insertBatch(list, m, "test_for_index1");
        insertBatch(list, m, "test_for_index2");
    }
}
